import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;

/**
 * @Author YuanYuan
 * @Date 2022/10/11
 * @Time 12:41
 */
public class TeseDemo {
    //创建线程,通过线程来计算 1+2+3+...+1000

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        //使用Callable来定义一个任务
        Callable<Integer> callable = new Callable<Integer>() {
            @Override
            public Integer call() throws Exception {
                int sum = 0;
                for (int i = 1; i <= 1000; i++) {
                    sum+=i;
                }
                return sum;
            }
        };

        FutureTask futureTask = new FutureTask<>(callable);

        //创建线程,来执行上述任务
        //Thread的构造方法,不能直接传callable,还需要一个中间的类
        Thread thread = new Thread(futureTask);

        thread.start();
        //获取线程的计算结果
        //get方法会阻塞,直到 call 方法计算完毕, get 才会返回~
        System.out.println(futureTask.get());
    }
}
